// 翻译函数
async function translate(text) {
  try {
    const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=en|zh`;

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Translation response:', data);

    if (data.responseStatus === 200 && data.responseData) {
      return { 
        success: true, 
        translation: data.responseData.translatedText,
        // 如果有匹配度信息，显示它
        match: data.responseData.match ? `(匹配度: ${data.responseData.match}%)` : ''
      };
    }
    return { success: false, error: '翻译失败' };
  } catch (error) {
    console.error('Translation error:', error);
    return { success: false, error: error.message };
  }
}

// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "translateSelection",
    title: "翻译选中文本",
    contexts: ["selection"]
  });
});

// 监听右键菜单点击
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "translateSelection") {
    chrome.tabs.sendMessage(tab.id, {
      type: "showTranslation",
      text: info.selectionText
    });
  }
});

// 监听来自content script的翻译请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'translate') {
    translate(request.text)
      .then(response => sendResponse(response))
      .catch(error => sendResponse({ success: false, error: error.message }));
    return true;
  }
}); 